package com.kecheng.action;

import com.kecheng.com.utils.*;
import com.kecheng.com.yx.util.JsSign;
import com.kecheng.com.yx.util.WeixinUtil;
import com.kecheng.dao.CommonDao;
import com.kecheng.dao.PeizhiDao;
import com.kecheng.dao.TeamDao;
import com.kecheng.dto.WebCommonsResponse;
import com.kecheng.pojo.Code;
import com.kecheng.pojo.Peizhi;
import com.kecheng.pojo.Team;
import com.kecheng.util.Delemoji;
import com.kecheng.util.ImgCompress;
import com.kecheng.util.SpringUtil;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 这个是所有action的基类（包含:预支付、获取openid和头像、分享、日志、cookie、session、上传压缩图片）
 * @author yunxin
 *
 */
public class BaseAction extends ActionSupport implements SessionAware {
	@Value("${static.host}")
	protected String StaticHost;
	@Value("${img.root}")
	public  String root;//图片突出的文件夹路径
	@Value("${wx.cert}")
	public String KEYSTORE_FILE;//证书位置

	//日志对象
	Log log = LogFactory.getLog( this .getClass()); 
	
	protected static final HttpServletRequest HttpServletRequest = null;

	
	protected Map<String, Object> session;
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected WebCommonsResponse webCommonsResponse;

	protected String msg;//页面提示信息 
	protected String title; //页面标题  需要时使用
	protected Integer min; // 分页时显示的最小值
	protected Integer max; // 分页时显示的最大最
	protected Integer page; // 分页时当前页面
	protected Integer allpage; // 分页时总页面
	protected Integer pagesize; // 分页大小

	protected String openid; // 用户标识
	protected String code; //接口权限码
	protected Team team;
	protected PeizhiDao peizhiDao = (PeizhiDao) SpringUtil.getBean("peizhiDao");
	public Peizhi peizhi = peizhiDao.find();
	@Autowired
	protected TeamDao teamDao;
	@Autowired
	protected CommonDao dao;
	
	/**
	 * 预支付接口的封装
	 */
	protected void yuzhifu(double money,String out_trade_no,String openid){
		 //总金额以分为单位，不带小数点
		String finalmoney = (int)(money*100)+"";
		// 商户相关参数
		String appid = peizhi.getAppid();
		String appsecret = peizhi.getAppsecret();
		String partner = peizhi.getPartner();
		String partnerkey = peizhi.getPartnerkey();
		// 获取openId后调用统一支付接口https://api.mch.weixin.qq.com/pay/unifiedorder
		String currTime = TenpayUtil.getCurrTime();
		// 8位日期
		String strTime = currTime.substring(8, currTime.length());
		// 四位随机数
		String strRandom = TenpayUtil.buildRandom(4) + "";
		// 10位序列号,可以自行调整。
		String strReq = strTime + strRandom;
		// 商户号
		String mch_id = partner;

		String nonce_str = strReq;
		// 商品描述根据情况修改(无要求就暂用公众号名称)
		String body = peizhi.getGzname();
		// 商户订单号
		// 订单生成的机器 IP
		String spbill_create_ip = org.apache.struts2.ServletActionContext
				.getRequest().getRemoteAddr();
		// = ((ServletRequest) request).getRemoteAddr();
		// 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
		String notify_url = "http://"+peizhi.getNetName()+"/notify1!notify1.com.kecheng.action";
		String trade_type = "JSAPI";
		
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("appid", appid);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("body", body);
		packageParams.put("out_trade_no", out_trade_no);
		packageParams.put("total_fee", finalmoney);//finalmoney
		packageParams.put("spbill_create_ip", spbill_create_ip);
		packageParams.put("notify_url", notify_url);
		packageParams.put("trade_type", trade_type);
		packageParams.put("openid", openid);

		HttpServletResponse HttpServletResponse = null;
		RequestHandler reqHandler = new RequestHandler(HttpServletRequest,
				HttpServletResponse);
		reqHandler.init(appid, appsecret, partnerkey);

		String sign = reqHandler.createSign(packageParams);
		String xml = "<xml>" + "<appid>" + appid + "</appid>" + "<mch_id>"
				+ mch_id + "</mch_id>" + "<nonce_str>" + nonce_str
				+ "</nonce_str>" + "<sign>" + sign + "</sign>"
				+ "<body><![CDATA[" + body + "]]></body>"
				+ "<out_trade_no>" + out_trade_no + "</out_trade_no>"
				+ "<total_fee>" + finalmoney + "</total_fee>"//finalmoney
				+ "<spbill_create_ip>" + spbill_create_ip
				+ "</spbill_create_ip>" + "<notify_url>" + notify_url
				+ "</notify_url>" + "<trade_type>" + trade_type
				+ "</trade_type>" + "<openid>" + openid + "</openid>"
				+ "</xml>";
		String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		String prepay_id = "";
		try {
			prepay_id = new GetWxOrderno().getPayNo(createOrderURL, xml);
			if (prepay_id.equals("")) {
				msg = "统一支付接口获取预支付订单出错";
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			log.error("统一支付接口获取预支付订单出错:"+e1);
		}
		SortedMap<String, String> finalpackage = new TreeMap<String, String>();
		String timestamp = Sha1Util.getTimeStamp();
		String nonceStr2 = nonce_str;
		String prepay_id2 = "prepay_id=" + prepay_id;
		String packages = prepay_id2;

		finalpackage.put("appId", appid);
		finalpackage.put("timeStamp", timestamp);
		finalpackage.put("nonceStr", nonceStr2);
		finalpackage.put("package", packages);
		finalpackage.put("signType", "MD5");
		String finalsign = reqHandler.createSign(finalpackage);

		session.put("package", packages);
		session.put("sign", finalsign);
		session.put("appid", appid);
		session.put("timeStamp", timestamp);
		session.put("nonceStr", nonceStr2);
	}
	
	/**
	 * Cookieの追加
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	public void addCookie(String name,String value) throws UnsupportedEncodingException{
		Cookie cookie = new Cookie(name, URLEncoder.encode(value, "utf-8"));
	    cookie.setMaxAge(60*60*24*365);
	    ServletActionContext.getResponse().addCookie(cookie);
	}
	public String getCookie(String name) throws UnsupportedEncodingException{
		//Cookie cookie = new Cookie(name, value);
		//cookie.setMaxAge(60*60*24*365);
		Cookie[] cookies = ServletActionContext.getRequest().getCookies();//这样便可以获取一个cookie数组
		if(cookies!=null&&cookies.length!=0){
			for(Cookie cookie : cookies){
				if(name.equals(cookie.getName())){
					String value = cookie.getValue();
					System.err.println("value:::"+value);
					value = URLDecoder.decode(value,"utf-8");
					return value;
				}
			}
		}
		return null;
	}

	/**
	 * 压缩图片
	 * @param file
	 * @param fileFileName
	 * @return
	 * @throws IOException
	 */
	protected String compressFile(File file, String fileFileName,Integer width) {
		try {
			fileFileName = System.currentTimeMillis() + fileFileName;
			//压缩图片啦
			String imgUrl = ImgCompress.compress(file, fileFileName,width);
			return imgUrl;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			log.error("上传图片异常:"+e);
		}
		return "";
	}

	/**
	 * 设置分页
	 */
	public void setpage() {
		if (page == null || page < 1) {
			page = 1;
		}
		if (allpage==null || allpage < 1 ) {
			allpage = 1;
		}
		page = Math.min(page, allpage);
		max = Math.min(page + 5, allpage);
		min = Math.max(1, page - 5);
	}

	/**
	 * 可通过code获取openid 若没有team 创建team
	 * 
	 * @throws IOException
	 */
	protected void loadOpenid() throws UnsupportedEncodingException {
		Code c = null;
		if(code == null) {
			return;
		}else{
			c =new Code();
			c.setCode(code);
			c = (Code) dao.findOne(c,"code");
			if(c!=null){
				return;
			}
		}
		System.out.println("======================================================================");
		c =new Code();
		c.setCode(code);
		dao.add(c);
		
		try {
			String appid = peizhi.getAppid();
			String appsecret = peizhi.getAppsecret();
			String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?"
				+ "appid=" + appid + "&secret=" + appsecret + "&code=" + code
				+ "&grant_type=authorization_code";
			
			JSONObject jsonObject = CommonUtil.httpsRequest(URL, "GET", null);
			openid = jsonObject.getString("openid");
			System.out.println("=[==================="+openid);
			if (openid != null && !"".equals(openid)) {
				addCookie("openid", openid);
			}
			/* 查询team */
			team = teamDao.findbysellerid(openid);
			if (team == null) {
				team = new Team();
				//补充参数
				team.init();
				team.setOpenid(openid);
				dao.add(team);
			}
			if ("snsapi_userinfo".equals(jsonObject.getString("scope"))) {
				String access_token = jsonObject.getString("access_token");
				String url1 = "https://api.weixin.qq.com/sns/userinfo?access_token="
						+ access_token + "&openid=" + openid + "&lang=zh_CN";
				JSONObject jsonObject1 = CommonUtil.httpsRequest(url1, "GET",
						null);
				openid = jsonObject1.getString("openid");
				String sex=jsonObject1.getString("sex");
				String img = jsonObject1.getString("headimgurl");
				team.setSex(sex);
				team.setImg(img);
				String nickname = jsonObject1.getString("nickname");
				nickname = Delemoji.emojiChange(nickname);
				team.setNickname(nickname);
				dao.update(team);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取openid接口异常:"+e);
		}
	}
	/**
	 * 分享接口
	 */
	protected void fenxiang() {
		try{
			String jsapi_ticket=WeixinUtil.getJsapiTicket();
			
			HttpServletRequest request = ServletActionContext.getRequest();
			StringBuffer url = request.getRequestURL();
			if (request.getQueryString() != null) {
				url.append("?");
				url.append(request.getQueryString());
			}
			
			Map<String, String> ret = JsSign.sign(jsapi_ticket, url.toString());
			for (Map.Entry<String, String> entry : ret.entrySet()) {
				System.out.println(entry.getKey() + "," + entry.getValue());
				session.put(entry.getKey(), entry.getValue());
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			log.error("分享接口:"+e);
		}
	}
	
	public void setSession(Map<String, Object> session) {
		this.session = session;
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		StringBuffer url = request.getRequestURL();
		if (request.getQueryString() != null) {
			url.append("?");
			url.append(request.getQueryString());
		}
		request.setAttribute("requestUrl", url.toString());
	}

	public Integer getPage() {
		return page;
	}

	public void setPage(Integer page) {
		this.page = page;
	}

	public Integer getAllpage() {
		return allpage;
	}

	public void setAllpage(Integer allpage) {
		this.allpage = allpage;
	}

	public Integer getPagesize() {
		return pagesize;
	}

	public void setPagesize(Integer pagesize) {
		this.pagesize = pagesize;
	}

	public Map<String, Object> getSession() {
		return session;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getOpenid() {
		return openid;
	}

	public void setOpenid(String openid) {
		this.openid = openid;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public Team getTeam() {
		return team;
	}

	public void setTeam(Team team) {
		this.team = team;
	}

	public Integer getMin() {
		return min;
	}

	public void setMin(Integer min) {
		this.min = min;
	}

	public Integer getMax() {
		return max;
	}

	public void setMax(Integer max) {
		this.max = max;
	}

	public static HttpServletRequest getHttpservletrequest() {
		return HttpServletRequest;
	}

	public String getStaticHost() {
		return StaticHost;
	}

	public WebCommonsResponse getWebCommonsResponse() {
		return webCommonsResponse;
	}

	public void setWebCommonsResponse(WebCommonsResponse webCommonsResponse) {
		this.webCommonsResponse = webCommonsResponse;
	}
}
